package ui;

import java.io.IOException;
import java.util.Scanner;

import org.jsoup.Jsoup;

import page.PageAnalyzer;
import page.PageParser;
import page.PageRetriever;


/**
 * @author Vladimir Dudnic, Derek Fleener, Michael Groenier
 *
 */
public class UI
{
       
        private PageRetriever retriever;
        private PageParser parser;
        private PageAnalyzer analyzer;
        boolean quittingTime = false;
        /** 
         * PageRetriever thread. 
         */
        private Thread retriever_thread;
       
        /** 
         * PagePaser thread. 
         */
        private Thread parser_thread;
       
        /** 
         * PageAnalyzer thread.
         */
        private Thread analyzer_thread;
        
        /**
         * Reads the users input.
         */
        private final Scanner my_console = new Scanner(System.in);
        
        long end;
        long total;
        
        /**
         * Starting URL
         */
        private String urlString = "";
        
        /**
         * Keyword list
         * @throws IOException
         */     
        public static void main(String args[]) throws InterruptedException, IOException
        {
                @SuppressWarnings("unused")
				UI ui = new UI();
        }
        /**
         * The constructor for this UI.
         * @throws InterruptedException
         * @throws IOException
         */
        public UI() throws InterruptedException, IOException
        {
                readInputURL();
                boolean correctURL = false;
                while (!correctURL)
                {
                        try 
                        {
                                Jsoup.connect(urlString).get();
                                correctURL = true;
                        } 
                        catch (IllegalArgumentException e) 
                        {
                                System.out.println("Not a valid url, please type in a new one");
                                readInputURL();
                        } 
                        catch (IOException e) 
                        {
                                System.out.println("Not a valid url, please type in a new one");
                                readInputURL();
                        }
                }
                try 
                {
                        retriever = new PageRetriever(urlString);
                } 
                catch (IOException e)
                {
                       
                }
                parser = new PageParser(retriever);
                analyzer = new PageAnalyzer(parser);
                 
                retriever_thread = new Thread(retriever);
                parser_thread = new Thread(parser);
                analyzer_thread = new Thread(analyzer);
               
                readInputKeywords();
                long start = System.currentTimeMillis();
                
                retriever_thread.start();
                parser_thread.start();
                analyzer_thread.start();
                
                System.out.println("Type in any key and press enter to quit the crawling");
                my_console.next();
               
                forceQuitAll();
                retriever_thread.interrupt();
                parser_thread.interrupt();
                analyzer_thread.interrupt();
                
                long end = System.currentTimeMillis();
                total = end - start;
                printResults();
        }
       /**
        * Halts the program.
        */
        private void forceQuitAll()
        {
                retriever.forceQuit();
                parser.forceQuit();
                analyzer.forceQuit();
        }

        private void readInputURL()
        {
                System.out.println("Please type the URL address of where you would like the crawling to begin: ");
                if (my_console.hasNext())
                {
                        urlString = my_console.next();
                }               
        }
       
        private void readInputKeywords()
        {
                boolean loop = true;
                do 
                {
                        System.out.println("Please type a keyword to be searched.");
               
                        if (analyzer.getKeywords().size() <= 10) 
                        {
                                analyzer.addKeyword(my_console.next());
                        }
                        System.out.println("Would you like to add more keywords?");
                        System.out.println("Press 1 for yes");
                        System.out.println("Press 2 for no");
                        int next = my_console.nextInt();
                        if (next >= 2)
                        {
                                loop = false;
                        }
                } 
                while (loop);
       
        }
       /**
        * Prints the results of the search.
        */
        private void printResults()
        {
            System.out.println("Pages retrieved: " + analyzer.getPagesRetrieved());
            System.out.println("Average words per page: " + analyzer.getAvgWords());
            System.out.println("Average URLs per page: " + analyzer.getAvgURLs());
            System.out.println("Keyword \t Total hits \t Avg. hits per page");
            String keyword;
            for (int i = 0; i < analyzer.getKeywords().size(); i++) 
            {
                    keyword = analyzer.getKeywords().get(i);
                    System.out.print(keyword + ": \t\t\t");
                    System.out.print(analyzer.getTotalHits(keyword) + "\t\t\t");
                    System.out.println(analyzer.getAvgHits(keyword));
            }
            System.out.println("Average parse time per page: " + (double) analyzer.getAvgParseTime()/1000 + " sec");
            System.out.println("Total running time: " + (double) total/1000 + " sec");
    }


}

